package com.ffyc.cms.controller;

import com.ffyc.cms.common.CommonResult;
import com.ffyc.cms.model.Admin;
import com.ffyc.cms.model.Company;
import com.ffyc.cms.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * 公司信息
 */
@RestController
@RequestMapping(path = "company")
public class CompanyController {
    @Autowired
    CompanyService companyService;

    @GetMapping(path = "getwebmsg")
    public CommonResult getWebMsg(){
        CommonResult commonResult = null;
        try{
            Company company;
            company  = companyService.getCompany();
            commonResult = new CommonResult(200,"查找成功",company);
            return commonResult;
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult(500,"服务器忙，请稍后重试",null);
            return commonResult;
        }
    }

    @PostMapping(path = "savewebmsg")
    public CommonResult savewebmsg(Company company,HttpSession session){
        CommonResult commonResult = null;
        try{
            Admin admin = (Admin)session.getAttribute("admin");
            companyService.savewebmsg(company,admin);
            commonResult = new CommonResult(200,"保存成功",null);
            return commonResult;
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult(500,"服务器忙，请稍后重试",null);
            return commonResult;
        }
    }

    @PostMapping(path = "/fileUpload")
    public CommonResult fileUpload(@RequestParam("fileName") CommonsMultipartFile file , HttpSession session){
        CommonResult commonResult = null;
        File f0 = new File("C:\\userImg\\companyLogo");
        if (!f0.exists()){
            f0.mkdir();
        }
        String oldFileName = file.getOriginalFilename();
        File f1 = new File(f0,oldFileName);//输出路径
        try {
            file.transferTo(f1);
            commonResult = new CommonResult(200,"上传成功",oldFileName);
        } catch (IOException e) {
            e.printStackTrace();
            commonResult = new CommonResult(500,"上传失败",null);
        }
        return commonResult;
    }
}
